package com.ruoyi.study.timedtask;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.sql.DbOperate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.io.IOException;

/**
 * 定时备份数据库
 * @author Administrator
 */
@Slf4j
@Configuration
@EnableScheduling
public class DbBackupTask {
    @Value("${spring.datasource.druid.master.url}")
    private String url;
    @Value("${backup.username}")
    private String username;
    @Value("${backup.password}")
    private String password;
    @Value("${backup.dir}")
    private String dir;
    @Value("${ruoyi.name}")
    private String projectName;
    @Scheduled(cron = "0 0 23 * * ?")
    @Transactional( propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void backupTask() throws IOException {
        log.info(url);
        String[] split = url.split("\\?");
        String[] split1 = split[0].split("//");
        String[] split2 = split1[1].split("/");
        String[] split3 = split2[0].split(":");
        String dbName= split2[1];
        String port= split3[1];
        String hostIp= split3[0];
        log.info("数据库开始备份");
        DbOperate.backUp(hostIp,port,username,password,dbName,dir+projectName+"/"+ DateUtils.getDate()+"/",dbName+"-"+ DateUtils.dateTimeNow()+".sql");
        log.info("数据库结束备份");
    }

}
